import os
import cv2
import base64
from pandas.core import base
import pandas as pd

class Choice(object):
    def __init__(self,li=[]):
        self.uuid=li[0]
        self.main=li[1]
        self.figure=li[2]
        self.a=li[3]
        self.b=li[4]
        self.c=li[5]
        self.d=li[6]
        self.answer=li[7]
        self.solution=li[8]
        self.score=li[9]
        self.latex=''
        self._get_latex()
    def _get_latex(self):
        #\question[6] 质量为$1.5\times 10^3kg$的汽车在水平路面上匀速行驶，速度为$20m/s$，受到的阻力大小为$1.8\times 10^3N.$此时，汽车发动机输出的实际功率是\key{C}
        # \fourchoices{$90W	$}{$30kW	$}{$36kW	$}{$300kW$}
        # \begin{solution}{4cm}
        # \end{solution}
        

        p1=r'\question[%s] %s\key{%s}'%(self.score,self.main,self.answer)+'\n'
        p2=''
        if self.figure!=None:
            with open('.'+os.sep+'temp'+os.sep+str(self.uuid)+".jpg","wb") as f:
                f.write(base64.b64decode(self.figure))
                f.close()
            p2=r'\begin{center}'+'\n'+r'\includegraphics[]{temp/'+str(self.uuid)+'.jpg}'+'\n'+r'\end{center}'
        p3=''
        if self.a!=None:
            p3=r'\fourchoices{%s}{%s}{%s}{%s}'%(self.a,self.b,self.c,self.d)+'\n'
        p4=''
        if self.solution!=None:
            p4=r'\begin{solution}{4cm}'+'\n'+str(self.solution)+r'\end{solution}'
        self.latex=p1+p2+p3+p4


class Essay(object):
    def __init__(self,args=[]):
        self.uuid=args[0]
        self.main=args[1]
        self.figure=args[2]
        self.answer=args[3]
        self.solution=args[4]
        self.score=args[5]
        self.latex=''
        self._get_latex()
    def _get_latex(self):
        #\question[6] 质量为$1.5\times 10^3kg$的汽车在水平路面上匀速行驶，速度为$20m/s$，受到的阻力大小为$1.8\times 10^3N.$此时，汽车发动机输出的实际功率是\key{C}
        # \fourchoices{$90W	$}{$30kW	$}{$36kW	$}{$300kW$}
        # \begin{solution}{4cm}
        # \end{solution}
        p1=r'\question{[%s]} %s'%(self.score,self.main)+'\n'
        p2=''
        if self.figure!=None:
            with open('.'+os.sep+'temp'+os.sep+str(self.uuid)+".jpg","wb") as f:
                f.write(base64.b64decode(self.figure))
                f.close()
            p2=r'\begin{center}'+'\n'+r'\includegraphics[]{temp/'+str(self.uuid)+'.jpg}'+'\n'+r'\end{center}'
        p3=''
        if self.solution!=None:
            p3=r'\begin{solution}{4cm}'+'\n'+str(self.solution)+r'\end{solution}'
        self.latex=p1+p2+p3


class Exam(object):
    def __init__(self,title='未命名'):
        self.title=''
        # li为uuid
        self.li_uuid=[]
        self.li_single_sel=[]
        self.li_multi_sel=[]
        self.li_essay=[]
        self.latex=''
        #
        self.p0=[r'\documentclass[list,adobe,answers]{BHCexam}',
            r'\pagestyle{fancy}',
            r'\fancyfoot[C]{\kaishu \small 第 \thepage 页 共 \pageref{lastpage} 页}',
            r'\fancyhead[L]{\includegraphics[width=2cm]{qrcode.png}\rightline{本试卷由开源项目\href{https://gitee.com/e13/gtexam}{GTexam}生成}}']
        self.p10=[r'\end{questions}',
            r'\end{groups}',
            r'\label{lastpage}',
            r'\end{document}']
        self.p_single=[]
        self.p_multi=[]
        self.p_essay=[]
    def get_li_uuid(self):
        pass
    def df_to_li(self,df_s,df_m,df_e):
        s=df_s[df_s['uuid'].isin(self.li_uuid)]
        m=df_m[df_m['uuid'].isin(self.li_uuid)]
        e=df_e[df_e['uuid'].isin(self.li_uuid)]
        for i in range(len(s)):
            self.li_single_sel.append(s.iloc[i,0])
            self.p_single.append(Choice(s.iloc[i].values).latex)
        for i in range(len(m)):
            self.li_multi_sel.append(m.iloc[i,0])
            self.p_multi.append(Choice(m.iloc[i].values).latex)
        for i in range(len(e)):
            self.li_essay.append(e.iloc[i,0])
            self.p_essay.append(Essay(e.iloc[i].values).latex)


class DefaultExam(Exam):
    def get_li_uuid(self,df,li_sub=[],li_year=[],li_degree=[]):
        t=pd.DataFrame()
        if li_sub!=[]:
            for i in li_sub:
                t.append(df[df['subject']==i]) 
        if li_year!=[]:
            for i in li_year:
                t.append(df[df['year']==i]) 
        if li_degree!=[]:
            for i in li_degree:
                t.append(df[df['degree']==i])
        pass
        self.li_uuid=t['uuid'].tolist()
    def get_latex(self):
        t=len(self.li_single_sel)
        p1_pre=[r'\begin{document}',
            r'{\heiti{绝密\ding{72}启用前}}',
            r'\title{'+str(self.year)+r'年普通高等学校招生全国统一考试}',
            r'\subtitle{理科综合能力测试(物理)}',
            r'\maketitle',
            r'{\heiti{注意事项：}}',
            r'\setlength\parindent{2em}',
            '\n',
            r'1. 答卷前，考生务必将自己的姓名、准考证号填写在答题卡上。',
            '\n',
            r'2. 回答选择题时，选出每小题答案后，用铅笔把答题卡上对应题目的答案标号涂黑，如需改动，用橡皮擦干净后，再选涂其它答案标号。回答非选择题时，将答案写在答题卡上，写在本试卷上无效。',
            '\n',
            r'3. 考试结束后，将本试卷和答题卡一并交回。',
            r'\begin{groups}',
            r'\group{选择题}{本题共8小题，每小题 6 分。共 48 分。在每小题给出的四个选项中，第 1\textasciitilde' +str(t)+ '题只有一项符合题目要求，第'+str(t+1) +r'\textasciitilde 8 题有多项符合题目要求。全部选对的得 6 分，选对但不全的得 3 分，有选错的得0分。}',
            r'\begin{questions}[30]']
        # p1=[]
        # for i in self.li_single_sel:
        #     p1.append(i.get_latex())
        # for i in self.li_multi_sel:
        #     p1.append(i.get_latex())
        p2_pre=[r'\end{questions}',
                r'\newpage',
                r'\group{非选择题}{共 174 分，第 9\textasciitilde 12 题为必考题，每个试题考生都必须作答。第 13\textasciitilde16 题为选考题，考生根 据要求作答。}',
                r'\begin{questions}[p]']
        # p2=[]
        # for i in self.li_essay:
        #     p2.append(i.get_latex())

        for i in [self.p0,p1_pre,self.p_single,self.p_multi,p2_pre,self.p_essay,self.p10]:
            for j in i:
                self.latex+=str(j)+'\n'
class ExamU(Exam):
    def get_li_uuid(self,df,year,no):
        if no==1:
            no_str='I'
            paper_name='U1'
        elif no==2:
            no_str='II'
            paper_name='U2'
        else:
            no_str='III'
            paper_name='U3'
        df1=df[df['year']==year]
        self.title=str(year)+'年全国{}卷'.format(no_str)
        self.year=year
        self.li_uuid=df1[df1['from_paper']==paper_name]['uuid'].tolist()
    def get_latex(self):
        t=len(self.li_single_sel)
        p1_pre=[r'\begin{document}',
            r'{\heiti{绝密\ding{72}启用前}}',
            r'\title{'+str(self.year)+r'年普通高等学校招生全国统一考试}',
            r'\subtitle{理科综合能力测试(物理)}',
            r'\maketitle',
            r'{\heiti{注意事项：}}',
            r'\setlength\parindent{2em}',
            '\n',
            r'1. 答卷前，考生务必将自己的姓名、准考证号填写在答题卡上。',
            '\n',
            r'2. 回答选择题时，选出每小题答案后，用铅笔把答题卡上对应题目的答案标号涂黑，如需改动，用橡皮擦干净后，再选涂其它答案标号。回答非选择题时，将答案写在答题卡上，写在本试卷上无效。',
            '\n',
            r'3. 考试结束后，将本试卷和答题卡一并交回。',
            r'\begin{groups}',
            r'\group{选择题}{本题共8小题，每小题 6 分。共 48 分。在每小题给出的四个选项中，第 1\textasciitilde' +str(t)+ '题只有一项符合题目要求，第'+str(t+1) +r'\textasciitilde 8 题有多项符合题目要求。全部选对的得 6 分，选对但不全的得 3 分，有选错的得0分。}',
            r'\begin{questions}[30]']
        # p1=[]
        # for i in self.li_single_sel:
        #     p1.append(i.get_latex())
        # for i in self.li_multi_sel:
        #     p1.append(i.get_latex())
        p2_pre=[r'\end{questions}',
                r'\newpage',
                r'\group{非选择题}{共 174 分，第 9\textasciitilde 12 题为必考题，每个试题考生都必须作答。第 13\textasciitilde16 题为选考题，考生根 据要求作答。}',
                r'\begin{questions}[p]']
        # p2=[]
        # for i in self.li_essay:
        #     p2.append(i.get_latex())

        for i in [self.p0,p1_pre,self.p_single,self.p_multi,p2_pre,self.p_essay,self.p10]:
            for j in i:
                self.latex+=str(j)+'\n'